﻿namespace GreenIsomer.Data.Entities.Ddl {
	using System;
	using System.Xml.Serialization;
	using System.Xml;
	using System.IO;
	using System.Text;
	using System.Globalization;

	[Serializable, XmlType("CreateScriptGenerator", Namespace = Settings.Namespace)]
	public class CreateScriptGenerator : ScriptGenerator {

		[NonSerialized]
		private SsdlInput ssdlInput;

		public CreateScriptGenerator() {
			ssdlInput = new SsdlInput();
		}

		[XmlAttribute("SsdlInputFile")]
		public string SsdlInputFile { get; set; }

		public override void Generate(string baseDirectory, ExtendedDefinition extendedDefinition, ProviderSettingsCollection providerSettings) {

			ssdlInput.Load(baseDirectory, SsdlInputFile);

			TableCollection tables = ssdlInput.GetTables();
			tables.MergeExtendedDefinition(extendedDefinition);

			ProviderSettings referencedProviderSettings = ssdlInput.GetReferencedProviderSettings(providerSettings);
			if(referencedProviderSettings != null && referencedProviderSettings.TypeConversions.Count != 0)
				tables.ReplaceDataTypes(referencedProviderSettings.TypeConversions);

			using(StreamWriter streamWriter = new StreamWriter(Generator.ResolvePath(baseDirectory, ScriptOutputFile), false, Encoding.UTF8))
			using(DdlWriter writer = new DdlWriter(streamWriter, referencedProviderSettings)) {

				writer.StartSection("Tables");

				foreach(Table table in tables) {
					if(table.SuppressDdlOutput) continue;

					table.WriteCreateScript(writer);
				}

				writer.StartSection("Data");

				foreach(DefinitionData data in extendedDefinition.Data) {
					writer.SkipLine();
					data.WriteCreateScript(writer, tables);
				}

				writer.StartSection("Foreign Keys");

				foreach(Table table in tables) {
					if(table.SuppressDdlOutput) continue;

					writer.SkipLine();

					foreach(ForeignKey foreignKey in table.ForeignKeys)
						foreignKey.WriteCreateScript(writer, table.Name, table.Schema);
				}

			}

		}

	}

}